<template>
  <div class="sale-add-container">
    <!-- 操作按钮区 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button @click="handleCancel">撤销</el-button>
    </div>
    <!-- 表单区 -->
    <el-card class="form-card" shadow="never">
      <el-form :model="form" label-width="90px" class="sale-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="销售日期" required>
              <el-date-picker v-model="form.SaleDate" type="date" placeholder="请选择销售日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户" required>
              <el-select v-model="form.CustomerId" placeholder="请选择客户" filterable>
                <el-option v-for="item in customerList" :key="item.Id" :label="item.Name" :value="item.Id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售员" required>
              <el-select v-model="form.SalesmanId" placeholder="请选择销售员" filterable>
                <el-option v-for="item in userList" :key="item.UserId" :label="item.UserName" :value="item.UserId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核状态">
              <el-select v-model="form.Status" placeholder="请选择审核状态">
                <el-option label="未审核" value="未审核" />
                <el-option label="已审核" value="已审核" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="收货地址">
              <el-input v-model="form.Address" placeholder="请输入收货地址" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据号">
              <el-input v-model="form.OrderNumber" placeholder="--" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="流水号">
              <el-input v-model="form.SerialNumber" placeholder="--" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <!-- 明细表格区 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="form.details" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="EarNumber" label="耳号" width="120" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.EarNumber" placeholder="耳号" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="TransactionPrice" label="成交价(元)" width="100" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.TransactionPrice" :min="0" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="FixedPrice" label="定价(元)" width="100" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.FixedPrice" :min="0" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="DiscountRate" label="折扣比例" width="80" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.DiscountRate" :min="0" :max="1" :step="0.01" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="Grade" label="等级" width="80" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.Grade" placeholder="等级" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="Breed" label="品种" width="100" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.Breed" placeholder="品种" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="Gender" label="性别" width="80" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.Gender" placeholder="请选择" size="small">
              <el-option label="公" value="公" />
              <el-option label="母" value="母" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="SheepTypeId" label="羊只类型" width="120" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.SheepTypeId" placeholder="请选择羊只类型" size="small">
              <el-option v-for="item in sheepTypeList" :key="item.Id" :label="item.TypeName || item.Name" :value="item.Id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="Status" label="繁殖状态" width="100" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.Status" placeholder="繁殖状态" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="PenId" label="栋舍" width="100" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.PenId" placeholder="请选择栋舍" size="small">
              <el-option v-for="item in penList" :key="item.House_typeId" :label="item.DongsheName" :value="item.House_typeId" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="PenPosition" label="栏位" width="100" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.PenPosition" placeholder="栏位" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="BirthDate" label="出生日期" width="120" align="center">
          <template #default="scope">
            <el-date-picker v-model="scope.row.BirthDate" type="date" placeholder="出生日期" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="BirthWeight" label="出生重(kg)" width="100" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.BirthWeight" :min="0" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="WeaningWeight" label="断奶重(kg)" width="100" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.WeaningWeight" :min="0" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="FatherNumber" label="父号" width="100" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.FatherNumber" placeholder="父号" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="MotherNumber" label="母号" width="100" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.MotherNumber" placeholder="母号" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="MonthAge" label="月龄" width="80" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.MonthAge" :min="0" size="small" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center">
          <template #default="scope">
            <el-button type="danger" size="small" @click="removeDetail(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button @click="addDetail" style="margin-top: 8px;">+ 增行</el-button>
    </el-card>
    <!-- 合计区 -->
    <div class="summary-section">
      <span>合计金额：{{ totalAmount.toFixed(2) }}</span>
    </div>
    <!-- 备注区 -->
    <el-card class="remark-card" shadow="never">
      <el-form-item label="备注">
        <el-input v-model="form.Remark" type="textarea" placeholder="请输入备注信息" />
      </el-form-item>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Sheep_BreedingWrite, serviceRead } from '@/utils/Interceptors'
import { useRoute, useRouter } from 'vue-router'

const customerList = ref<any[]>([])
const userList = ref<any[]>([])
const sheepTypeList = ref<any[]>([])
const penList = ref<any[]>([])

const form = reactive({
  SaleDate: '',
  CustomerId: '',
  SalesmanId: '',
  OrderNumber: '',
  Address: '',
  SerialNumber: '',
  Remark: '',
  Status: '', // 审核状态
  TransactionPrice: 0, // 总成交价
  details: [
    {
      EarNumber: '',
      TransactionPrice: 0,
      FixedPrice: 0,
      DiscountRate: 1,
      Grade: '',
      Breed: '',
      Gender: '',
      SheepTypeId: '',
      Status: '',
      PenId: '',
      PenPosition: '',
      BirthDate: '',
      BirthWeight: 0,
      WeaningWeight: 0,
      FatherNumber: '',
      MotherNumber: '',
      MonthAge: 0
    }
  ]
})

const detailTemplate = () => ({
  EarNumber: '',
  TransactionPrice: 0,
  FixedPrice: 0,
  DiscountRate: 1,
  Grade: '',
  Breed: '',
  Gender: '',
  SheepTypeId: '',
  Status: '',
  PenId: '',
  PenPosition: '',
  BirthDate: '',
  BirthWeight: 0,
  WeaningWeight: 0,
  FatherNumber: '',
  MotherNumber: '',
  MonthAge: 0
})

const addDetail = () => {
  form.details.push(detailTemplate())
}
const removeDetail = (index: number) => {
  form.details.splice(index, 1)
}
const totalAmount = computed(() =>
  form.details.reduce((sum, row) => sum + Number(row.TransactionPrice || 0), 0)
)

const fetchCustomerList = () => {
  Sheep_BreedingWrite.get('/api/Customer/GetCustomerList').then(res => {
    if (res.data && res.data.code === 200) {
      customerList.value = res.data.data || []
    } else {
      customerList.value = []
    }
  })
}
const fetchUserList = () => {
  serviceRead.get('/api/User/SraechUser').then(res => {
    if (res.data && res.data.code === 200) {
      userList.value = res.data.PageData || []
    } else {
      userList.value = []
    }
  })
}

const fetchSheepTypeList = () => {
  Sheep_BreedingWrite.get('/api/SheepType/List/list').then(res => {
    if (res.data && res.data.code === 200) {
      sheepTypeList.value = res.data.data || []
    } else {
      sheepTypeList.value = []
    }
  })
}

const fetchPenList = () => {
  Sheep_BreedingWrite.get('/api/Pen/List').then(res => {
    if (res.data && res.data.code === 200) {
      penList.value = res.data.data || []
    } else {
      penList.value = []
    }
  })
}

const handleSave = async () => {
  try {
    form.TransactionPrice = form.details.reduce((sum, row) => sum + Number(row.TransactionPrice || 0), 0)
    let res
    if (route.query.id) {
      // 编辑，调用更新接口
      res = await Sheep_BreedingWrite.put('/api/SheepSale/UpdateSheepSale', { ...form, Id: route.query.id })
    } else {
      // 新增
      res = await Sheep_BreedingWrite.post('/api/SheepSale/AddSheepSale', form)
    }
    if (res.data && res.data.code === 200) {
      ElMessage.success(res.data.msg || '保存成功')
      // 可选：跳转回列表
      router.push({ name: 'SaleView' })
    } else {
      ElMessage.error(res.data.msg || '保存失败')
    }
  } catch (e) {
    ElMessage.error(e?.response?.data?.msg || '请求失败')
  }
}
const handleCancel = () => {
  ElMessage.info('已撤销（示例）')
}

const route = useRoute()
const router = useRouter()

onMounted(() => {
  fetchCustomerList()
  fetchUserList()
  fetchSheepTypeList()
  fetchPenList()
  if (route.query.id) {
    // 编辑，拉取详情
    Sheep_BreedingWrite.get(`/api/SheepSale/GetSheepSaleById?id=${route.query.id}`).then(res => {
      if (res.data && res.data.code === 200) {
        Object.assign(form, res.data.data)
        if (res.data.data.details) {
          // 补全每一项字段，保证scope.row.xxx绑定正常
          form.details = res.data.data.details.map((item: any) => ({
            ...detailTemplate(),
            ...item
          }))
        }
      }
    })
  }
})
</script>

<style scoped>
.sale-add-container {
  min-height: 100vh;
  background: #f7f8fa;
  padding: 24px;
}
.action-bar {
  margin-bottom: 16px;
}
.form-card {
  margin-bottom: 18px;
}
.sale-form {
  padding: 12px 0;
}
.table-card {
  margin-bottom: 12px;
}
.summary-section {
  margin: 12px 0 18px 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}
.remark-card {
  margin-top: 12px;
}
</style> 